<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">

</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="finished">完成</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs data-count-edit" lay-event="rollback" data-title="填写退单原因">退单</a>
        </script>

    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="../../js/axios.min.js"></script>
<script>

    var engineerProvince, engineerCity, engineerArea, engineerId;
    axios.defaults.withCredentials = true


    layui.use(['form', 'table','layarea'], function () {
        //引入layui集成的包
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            layarea = layui.layarea;

        axios.get('http://localhost:8080/engineer/getEngineerAddress',{
            withCredentials: true
        }).then(function(res){
            var data = res.data.data
            console.log(data)
            /*返回数据实例
            {
                "code": 0,
                "count": 0,
             "data": {
                    "engineerProvince": "天津市",
                     "engineerCity": "天津市",
                       "engineerArea": "西青区"
                     }
            }
            * */

            layarea.render({
                elem: '#picker',

                data: {
                    province: data.engineerProvince,
                    city: data.engineerCity,
                    county: data.engineerArea
                },

            });
        })

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            var orderId = data.orderId;
            console.log(orderId);
            if (obj.event === 'finished') {
                var html = '<div id="uploadContainer">' +
                    '<div class="layui-upload">' +
                    '<input type="file" lay-verify="required" name="orderVerify" id="fileInput" style="display: none;">'+
                    '<button type="button" class="layui-btn" id="uploadBtn">选择文件</button>' +
                    '</div>' +
                    '</div>';

                layer.confirm(html, {
                    btn: ['确定', '取消'], // 自定义按钮文本
                    shadeClose: true,
                    success: function(layero, index) {

                        var file = null;

                        document.getElementById('uploadBtn').addEventListener('click', function() {
                            document.getElementById('fileInput').click();
                        });


                        document.getElementById('fileInput').addEventListener('change', function() {
                            file = this.files[0];
                        });


                        // 确定按钮的点击事件处理
                        layero.find('.layui-layer-btn0').on('click', function() {
                            // 获取选择的文件
                            if (file) {
                                uploadFile(file, orderId);
                            }
                        });
                    }
                }, function (index) {
                    layer.close(index);
                });
                function uploadFile(file,orderId) {
                    var formData = new FormData();
                    formData.append('orderVerify', file);
                    formData.append('orderId', orderId); // 添加 orderId 参数

                    axios.post('http://localhost:8080/order/verify', formData, {
                        withCredentials: true,
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }).then(function (response) {
                        // 接单成功，显示成功提示信息
                        var output = response.data.code;
                        if (output === 0) {
                            layer.msg("已完成，待商家确认");
                            table.reload('currentTableId');
                        }
                    }).catch(function (error) {
                        // 接单失败，显示失败提示信息
                        layer.msg("发生错误，请稍后再试");
                        table.reload('currentTableId');
                    });
                }
                return false;
            }
            else if (obj.event === 'rollback') {
                var title = $(this).data('title'); // 获取弹窗标题

                layer.prompt({
                    formType: 2,
                    title: title,
                    area: ['400px', '200px'],
                    btn: ['确认', '取消'],
                    yes: function (index, layero) {
                        var reason = layero.find('.layui-layer-input').val();
                        var formData = new FormData();
                        formData.append("orderId", orderId);
                        formData.append("reason", reason);
                        if (reason) {
                            // 提交退单请求
                            axios.post('http://localhost:8080/order/returnOrder',formData , {
                                withCredentials: true
                            }).then(function (response) {
                                var output = response.data.data;
                                if (output === "发起退单申请成功") {
                                    layer.msg("退单申请已提交");
                                    table.reload('currentTableId');
                                }
                            }).catch(function (error) {
                                layer.msg("发生错误，请稍后再试");
                                table.reload('currentTableId');
                            });
                        } else {
                            layer.msg("请输入退单原因");
                        }
                        layer.close(index);
                    }
                });
                return false;
            }
        });

        axios.get('http://localhost:8080/order/getOrdersNowEngineer', {
            withCredentials: true

        })
            .then(function (response) {
                // 请求成功的处理逻辑
                var tableData = response.data.data;
                // 定义每页显示的数量和当前页码
                var pageSize = 10; // 每页显示10条数据
                var currentPage = 1; // 当前页码为1

                // 计算需要显示的数据范围
                var startIndex = (currentPage - 1) * pageSize;
                var endIndex = startIndex + pageSize;

                // 提取需要显示的数据
                var currentPageData = tableData.slice(startIndex, endIndex);


                // 定义数据表格的配置项
                var tableConfig = {
                    elem: '#currentTableId',
                    data: tableData, // 设置完整的数据列表
                    page: true, // 开启分页
                    limit: pageSize, // 每页显示的数量
                    cols: [[
//                        {type: "checkbox", width: 80},
                        {field: 'userName', width: 70, title: '用户'},
                        {field: 'orderClientname', width: 70, title: '姓名'},
                        {field: 'productType', width: 130, title: '产品型号', sort: true},
                        {field: 'orderDescription', width: 200, title: '订单描述'},
                        {field: 'orderPriority', width: 100, title: '优先级',sort: true, templet: '#priorTpl', sort: true},
                        {field: 'orderClientphone', width: 140, title: '用户手机号',},
//                        {field: 'orderDate', width: 110, title: '日期', sort: true},
//                        {field: 'orderTime', width: 110, title: '时间', templet: '#timeTpl', sort: true},
                        {field: 'orderDateTime', width: 160, title: '日期时间', templet: '#dateTimeTpl', sort: true},
                        {field: 'orderArea', width: 80, title: '区县'},
                        {field: 'orderAddress', width: 250, title: '详细地址',},
                        {title: '操作', minWidth: 50, toolbar: '#currentTableBar', align: "center"}
                    ]],
                    // 设置初始排序
                    initSort: {
                        field: 'orderPriority',
                        type: 'desc' // 降序排列
                    }
                };

                // 渲染表格
                var tableInstance = table.render(tableConfig);

                // 监听分页切换事件
                table.on('page(currentTableFilter)', function(obj) {
                    // 更新当前页码
                    currentPage = obj.curr;

                    // 计算需要显示的数据范围
                    var startIndex = (currentPage - 1) * pageSize;
                    var endIndex = startIndex + pageSize;

                    // 提取需要显示的数据
                    var currentPageData = dataList.slice(startIndex, endIndex);

                    // 更新表格数据
                    tableInstance.reload({
                        data: currentPageData
                    });
                });
                axios.get('http://localhost:8080/engineer/getEngineerAddress',{
                    withCredentials: true
                }).then(function(res){
                    var data = res.data.data
                    console.log(data)
                    /*返回数据实例
                    {
                        "code": 0,
                        "count": 0,
                     "data": {
                            "engineerProvince": "天津市",
                             "engineerCity": "天津市",
                               "engineerArea": "西青区"
                             }
                    }
                    * */

                    layarea.render({
                        elem: '#picker',

                        data: {
                            province: data.engineerProvince,
                            city: data.engineerCity,
                            county: data.engineerArea
                        },

                    });

                })

            })
            .catch(function (error) {
                console.log(document.cookie)
                // 请求失败的处理逻辑
                console.error(error);
            });



    });
    function formatTime(time) {
        if (time === 0) {
            return '上午';
        } else if (time === 1) {
            return '下午';
        } else if (time === 2) {
            return '晚上';
        } else {
            return '';
        }
    }
</script>
<script type="text/html" id="timeTpl">
    {{#  if(d.orderTime === 0){ }}
    上午
    {{#  } else if(d.orderTime === 1) { }}
    下午
    {{#  } else if(d.orderTime === 2) { }}
    晚上
    {{#  } }}
</script>
<script type="text/html" id="dateTimeTpl">
    {{ layui.util.toDateString(d.orderDate, 'yyyy-MM-dd') + ' ' + formatTime(d.orderTime) }}
</script>
<script type="text/html" id="priorTpl">
    {{#  if(d.orderPriority === 0){ }}
    正常
    {{#  } else if(d.orderPriority === 1) { }}
    较高
    {{#  } else if(d.orderPriority === 2) { }}
    高
    {{#  } else if(d.orderPriority === 3) { }}
    非常高
    {{#  } }}
</script>
</body>
</html>